<?php

namespace app\base\controller;

use app\admin\model\Classes;
use app\admin\model\Config;
use app\admin\model\Grade;
use app\admin\model\Paper;
use app\common\controller\AdminBase;
use app\base\model as modelBase;
use PHPExcel_Reader_Excel2007;
use PHPExcel_Reader_Excel5;
use PHPExcel_Shared_Date;
use PHPExcel_RichText_Run;
use PHPExcel_RichText;
use think\Exception;

class User extends AdminBase {
  private $model, $modelRole;

  public function __construct() {
    parent::__construct();
    $this->model = new modelBase\User();
    $this->modelRole = new modelBase\Role();
  }

  public function _initialize() {
    parent::_initialize(); // TODO: Change the autogenerated stub
  }

  public function index() {
    $search = input('search/a', []);
    $modelClass = new Classes();

    $map = ['role_id' => 3];
    if ($search) {
      if (isset($search['username'])) {
        $searchName = $search['username'];
        if (is_numeric($searchName)) {
          $map['u.username'] = ['like',
                                "%{$searchName}%"];
        } else {
          $map['u.realname'] = ['like',
                                "%{$searchName}%"];
        }
      }
      if ($search['class_id'] > 0) {
        $map['u.class_id'] = $search['class_id'];
      }
    }
    if ($this->roleId == 2) {
      $map['u.class_id'] = $modelClass->getTeacherClassId($this->uid);
    }
    //获取所有班级作为搜索条件
    $classes = $modelClass->column('title', 'id');
    $classes = ['--所有班级--'] + $classes;
    //
    $rows = $this->model->alias('u')
      ->where($map)
      ->join('__CLASS__ c', 'c.id=u.class_id', 'left')
      ->order('u.id DESC')
      ->field('u.*,c.title as class_title')
      ->paginate();


    return view('', [
      'rows'    => $rows,
      'search'  => $search,
      'classes' => $classes,
      'roleId'  => $this->roleId,
    ]);

  }

  public function add() {
    return self::edit();
  }

  public function edit() {
    $id = input('id/d', 0, 'abs');
    $modelClass = new Classes();

    if (!request()->isPost()) {
      $row = ($id > 0) ? $this->model->find($id) : [];
      $classes = $modelClass->column('title', 'id');

      //
      return view('edit', [
        'row'      => $row,
        'id'       => $id,
        'classes'  => $classes,
        'roleId'   => $this->roleId,
        'sexArr'   => config('sexArr'),
        'disabled' => $id > 0 ? 'disabled="disabled"' : '',
      ]);
    } else {
      $form = input('form/a', NULL, 'trim');
      $validate = new \app\base\validate\User();
      $result = $validate->scene($id > 0 ? 'edit' : 'add')->check($form);
      if (TRUE !== $result) {
        $this->error($validate->getError());
      }
      if ($this->roleId != 1) {
        $class_id = $modelClass->getTeacherClassId($this->uid);
        $form['class_id'] = $class_id;
      }
      $form['status'] = isset($form['status']) ? $form['status'] : 0;
      $r = $id > 0 ? $this->model->editUser($form, $id) : $this->model->addUser($form);

      if ($r !== TRUE) {
        $this->error(lang('error') . $r);
      }
      $this->success(lang('success'), url('index'));
    }
  }

  public function user_select_layer() {
    $filter = input('filter/a', NULL);
    $modelClass = new Classes();
    $map = ['u.status'  => 1,
            'u.role_id' => 3,
            'is_pass'   => 0];
    if ($filter) {
      if ($filter['classid']) {
        $map['u.class_id'] = $filter['classid'];
      }
    }
    if ($this->roleId == 1) {
      $map['exam_times'] = ['between',
                            [1,
                             3]];
    } else {
      $map['exam_times'] = 0;
    }
    $users = $this->model
      ->alias('u')
      ->where($map)
      ->join('__CLASS__ c', 'u.class_id=c.id', 'left')
      ->field('u.realname,u.class_id,u.id,c.title')
      ->select();

    $classAll = $modelClass->column('title', 'id');
    //
    $modelConfig = new Config();
    $userCpacity = $modelConfig->getNewest()['capacity'];
    $this->assign('users', json_encode($users));
    $this->assign('classAll', $classAll);
    $this->assign('userCpacity', $userCpacity);

    return view('');
  }

  public function import() {
    if ($this->roleId !== 1) {
      $this->error('非管理员不能使用该功能');
    }
    $fileId = input('file_id/d', 0, 'abs');
    if (!$fileId) {
      return view();
    }
    //
    $modelFile = new File();
    $fileInfo = $modelFile->getFile($fileId);
    $filename = url('/public/' . $fileInfo['filepath'], NULL, '');
    $filename = realpath("../") . $filename;
    //
    $modelClass = new Classes();
    if ($this->roleId == 2) {
      $classId = $modelClass->getTeacherClassId($this->uid);
      if (!$classId) $this->error('没有设定班级的班主任不能导入');
    }
    $classes = $modelClass->column('id', 'title');
    $objPHPExcelReader = new PHPExcel_Reader_Excel2007();
    if (!$objPHPExcelReader->canRead($filename)) {
      $objPHPExcelReader = new PHPExcel_Reader_Excel5();
      if (!$objPHPExcelReader->canRead($filename)) {
        $this->error('当前EXCEL文档的格式错误。' . $filename);
      }
    }
    $PHPExcel = $objPHPExcelReader->load($filename);
    $sheet = $PHPExcel->getSheet(0);
    $qData = [];
    foreach ($sheet->getRowIterator() as $k1 => $row) {
      if ($row->getRowIndex() < 2) continue; //跳过首行
      foreach ($row->getCellIterator() as $k2 => $cell) {
        $value = $cell->getValue();
        switch ($k2) {
          case 'A':
            $qData[ $k1 ]['username'] = $value;
            break;
          case 'B':
            $qData[ $k1 ]['realname'] = $value;
            break;
          case 'C':
            if ($this->roleId == 1) {
              $qData[ $k1 ]['class_id'] = $classes[ $value ];
            } else {
              $qData[ $k1 ]['class_id'] = $classId;
            }
            break;
          default:
            break;
        }
        $qData[ $k1 ]['salt'] = rand(100000, 999999);
        $qData[ $k1 ]['password'] = $this->model->createPassword(config('system')['default_password'], $qData[ $k1 ]['salt']);
      }
    }


    $r = $this->model->saveAll($qData);

    if ($r !== FALSE)
      $this->success(lang('success'), 'index');
    else
      $this->error(lang('error') . $this->model->getError());
  }

  public function batchDelete() {
    $ids = input('ids/a', []);
    if (!$ids)
      $this->error(lang('form empty'));
    $modelPaper = new Paper();
    $map['uid'] = ['in',
                   $ids];
    $papers = $modelPaper->where($map)->column('uid');
    $unique = array_unique($papers);

    $canDelete = array_diff($ids, $unique);
    if (!$canDelete) $this->error('所选择的考生已参加考试，无法删除');
    //
    $map = [];
    $map['id'] = ['in',
                  $canDelete];
    $userRealnames = $this->model->where($map)->column('realname', 'id');
    try {
      $this->model->where($map)->delete();
    } catch (Exception $e) {
      $this->error($e->getMessage());
    }
    $canDeleteNames = array_map(function ($v) use ($userRealnames) {
      return $userRealnames[ $v ];
    }, $canDelete);
    $this->success('部分考生已参加考试，无法删除，以下考生已被删除：' . implode('、', $canDeleteNames));
  }

  public function my() {
    $row = $this->model->find(session('user_id'));
    $this->result($row, 1);
  }

  public function resetpw() {
    $id = input('id/d', 0, 'abs');
    $row = $this->model->find($id);
    if (!$row) $this->error(lang('data empty'));
    $defPw = config('system')['default_password'];
    $pw = $this->model->createPassword($defPw, $row['salt']);
    $data = ['password' => $pw];
    try {
      $this->model->save($data, ['id' => $id]);
    } catch (Exception $e) {
      $this->error($e->getMessage());
    }
    $this->success('密码已经重置为' . $defPw);
  }
}
